#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :check.py
# @Time      :2024/8/28 17:20
# @Author    :Raink
from datetime import datetime,timedelta
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import pandas as pd
from weather_data import sql_conn
from settings import sender,password,receiver


def check_data():
    date=datetime.today().date()-timedelta(days=1)
    print(date)
    sql=f'''
    select * from weather_3_days where update_date='{date}'
    '''
    df=pd.read_sql(sql,sql_conn)

    print(len(df["name"].unique()))
    city_num=len(df["name"].unique())
    #reset_index是用来进行做dataframe的
    print(df.groupby(by="name")["id"].count().reset_index()["id"].unique())
    city_row_num=df.groupby(by="name")["id"].count().reset_index()["id"].unique()
    report=f"{date} weather_next_3_days:城市数量为{city_num},城市条目数列表:{city_row_num}"
    return report

def simple_email(data):
    # 邮件发送方信息
    senders = sender
    passwords = password

    # 邮件接收方信息
    receivers = receiver
    # 设置邮件内容
    message = MIMEText(f'{data}', 'plain', 'utf-8')
    message['From'] = senders
    message['To'] = receivers

    subject = '未来三天天气情况'
    message['Subject'] = Header(subject, 'utf-8')
    return sender,passwords,receivers,message
def send(sender,password,receivers,message):
    try:
        # 连接到SMTP服务器
        smtp_server = 'smtp.qq.com'  # 替换为你的SMTP服务器地址
        smtp_port = 465  # SSL端口
        smtpObj = smtplib.SMTP_SSL(smtp_server, smtp_port)

        # 登录SMTP服务器
        smtpObj.login(sender, password)

        # 发送邮件
        smtpObj.sendmail(sender, receivers, message.as_string())

        print("邮件发送成功")
        # 关闭连接
        smtpObj.quit()
    except smtplib.SMTPException as e:
        print("Error: 无法发送邮件", e)

def run_check():
    data=check_data()
    sender,password,receivers,message=simple_email(data)
    send(sender,password,receivers,message)
